package com.outdoor.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.outdoor.mapper.TeamMemberMapper;
import com.outdoor.model.dto.request.TeamCreateRequest;
import com.outdoor.model.dto.response.ApiResponse;
import com.outdoor.model.dto.response.TeamResponse;
import com.outdoor.model.entity.Team;
import com.outdoor.model.entity.User;
import com.outdoor.model.enums.ActivityType;
import com.outdoor.service.ApplicationService;
import com.outdoor.service.TeamService;
import com.outdoor.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

/**
 * 团队控制器
 * 
 * @author OutdoorTeam
 * @date 2025-05-18
 */
@Slf4j
@RestController
@RequestMapping("/api/teams")
@RequiredArgsConstructor
@Tag(name = "团队管理", description = "团队相关接口")
public class TeamController {

    private final TeamService teamService;
    private final UserService userService;
    private final ApplicationService applicationService;
    private final TeamMemberMapper teamMemberMapper;

    @PostMapping
    @Operation(summary = "创建团队", description = "创建新团队")
    public ApiResponse<TeamResponse> createTeam(@Valid @RequestBody TeamCreateRequest request) {
        // 模拟获取当前用户ID，实际项目中应从认证信息中获取
        Long currentUserId = 1L;
        log.debug("创建团队请求: {}", request.getName());
        
        Team team = teamService.createTeam(request, currentUserId);
        User leader = userService.getUserById(team.getLeaderId());
        
        // 新创建的团队只有领队一个成员
        int memberCount = 1;
        int pendingCount = 0;
        
        TeamResponse response = TeamResponse.fromEntityWithDetails(
            team, leader, memberCount, pendingCount);
        return ApiResponse.success("团队创建成功", response);
    }

    @GetMapping("/{id}")
    @Operation(summary = "获取团队", description = "根据ID获取团队信息")
    public ApiResponse<TeamResponse> getTeamById(@PathVariable Long id) {
        log.debug("获取团队请求: ID={}", id);
        Team team = teamService.getTeamById(id);
        
        // 获取领队信息
        User leader = userService.getUserById(team.getLeaderId());
        
        // 获取成员数量和待处理申请数量
        List<Long> memberIds = teamService.getTeamMemberIds(id);
        int memberCount = memberIds.size();
        int pendingCount = applicationService.getApplicationsByTeamAndStatus(id, 
            com.outdoor.model.enums.ApplicationStatus.PENDING).size();
        
        TeamResponse response = TeamResponse.fromEntityWithDetails(
            team, leader, memberCount, pendingCount);
        return ApiResponse.success(response);
    }

    @PutMapping("/{id}")
    @Operation(summary = "更新团队", description = "更新团队信息")
    public ApiResponse<TeamResponse> updateTeam(@PathVariable Long id, @Valid @RequestBody TeamCreateRequest request) {
        // 模拟获取当前用户ID
        Long currentUserId = 1L;
        log.debug("更新团队请求: ID={}", id);
        
        Team team = teamService.updateTeam(id, request, currentUserId);
        
        // 获取领队信息
        User leader = userService.getUserById(team.getLeaderId());
        
        // 获取成员数量和待处理申请数量
        List<Long> memberIds = teamService.getTeamMemberIds(id);
        int memberCount = memberIds.size();
        int pendingCount = applicationService.getApplicationsByTeamAndStatus(id, 
            com.outdoor.model.enums.ApplicationStatus.PENDING).size();
        
        TeamResponse response = TeamResponse.fromEntityWithDetails(
            team, leader, memberCount, pendingCount);
        return ApiResponse.success("团队更新成功", response);
    }

    @DeleteMapping("/{id}")
    @Operation(summary = "删除团队", description = "删除团队")
    public ApiResponse<Void> deleteTeam(@PathVariable Long id) {
        // 模拟获取当前用户ID
        Long currentUserId = 1L;
        log.debug("删除团队请求: ID={}", id);
        
        teamService.deleteTeam(id, currentUserId);
        return ApiResponse.success("团队删除成功", null);
    }

    @GetMapping("/leader/{userId}")
    @Operation(summary = "获取用户创建的团队", description = "获取指定用户创建的团队列表")
    public ApiResponse<IPage<TeamResponse>> getTeamsByLeader(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        log.debug("获取用户创建的团队请求: 用户ID={}", userId);
        
        Page<Team> page = new Page<>(current, size);
        IPage<Team> teams = teamService.getTeamsByLeader(userId, page);
        
        // 查询用户信息
        User leader = userService.getUserById(userId);
        
        IPage<TeamResponse> responseIPage = teams.convert(team -> {
            List<Long> memberIds = teamService.getTeamMemberIds(team.getId());
            int memberCount = memberIds.size();
            int pendingCount = applicationService.getApplicationsByTeamAndStatus(team.getId(), 
                com.outdoor.model.enums.ApplicationStatus.PENDING).size();
            
            return TeamResponse.fromEntityWithDetails(team, leader, memberCount, pendingCount);
        });
        
        return ApiResponse.success(responseIPage);
    }

    @GetMapping("/member/{userId}")
    @Operation(summary = "获取用户参与的团队", description = "获取指定用户参与的团队列表")
    public ApiResponse<IPage<TeamResponse>> getTeamsByMember(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        log.debug("获取用户参与的团队请求: 用户ID={}", userId);
        
        Page<Team> page = new Page<>(current, size);
        IPage<Team> teams = teamService.getTeamsByMember(userId, page);
        
        IPage<TeamResponse> responseIPage = teams.convert(team -> {
            User leader = userService.getUserById(team.getLeaderId());
            List<Long> memberIds = teamService.getTeamMemberIds(team.getId());
            int memberCount = memberIds.size();
            int pendingCount = applicationService.getApplicationsByTeamAndStatus(team.getId(), 
                com.outdoor.model.enums.ApplicationStatus.PENDING).size();
            
            return TeamResponse.fromEntityWithDetails(team, leader, memberCount, pendingCount);
        });
        
        return ApiResponse.success(responseIPage);
    }

    @GetMapping
    @Operation(summary = "查询团队", description = "根据条件查询团队列表")
    public ApiResponse<IPage<TeamResponse>> findTeams(
            @RequestParam(required = false) ActivityType activityType,
            @RequestParam(required = false) String location,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") long current,
            @RequestParam(defaultValue = "10") long size) {
        
        log.debug("查询团队请求: 活动类型={},关键词={}, 地点={}, 开始日期={}, 结束日期={}, 关键词={}",
                activityType,keyword, location, startDate, endDate, keyword);
        
        Page<Team> page = new Page<>(current, size);
        IPage<Team> teams = teamService.findTeams(activityType, location, startDate, endDate, keyword, page);
        
        IPage<TeamResponse> responseIPage = teams.convert(team -> {
            User leader = userService.getUserById(team.getLeaderId());
            List<Long> memberIds = teamService.getTeamMemberIds(team.getId());
            int memberCount = memberIds.size();
            int pendingCount = applicationService.getApplicationsByTeamAndStatus(team.getId(), 
                com.outdoor.model.enums.ApplicationStatus.PENDING).size();
            
            return TeamResponse.fromEntityWithDetails(team, leader, memberCount, pendingCount);
        });
        
        return ApiResponse.success(responseIPage);
    }

    @PostMapping("/{teamId}/join")
    @Operation(summary = "加入团队", description = "用户加入团队")
    public ApiResponse<TeamResponse> joinTeam(@PathVariable Long teamId) {
        // 模拟获取当前用户ID
        Long currentUserId = 1L;
        log.debug("加入团队请求: 团队ID={}, 用户ID={}", teamId, currentUserId);
        
        Team team = teamService.joinTeam(teamId, currentUserId);
        
        User leader = userService.getUserById(team.getLeaderId());
        List<Long> memberIds = teamService.getTeamMemberIds(teamId);
        int memberCount = memberIds.size();
        int pendingCount = applicationService.getApplicationsByTeamAndStatus(teamId, 
            com.outdoor.model.enums.ApplicationStatus.PENDING).size();
            
        TeamResponse response = TeamResponse.fromEntityWithDetails(
            team, leader, memberCount, pendingCount);
            
        return ApiResponse.success("成功加入团队", response);
    }

    @PostMapping("/{teamId}/leave")
    @Operation(summary = "退出团队", description = "用户退出团队")
    public ApiResponse<TeamResponse> leaveTeam(@PathVariable Long teamId) {
        // 模拟获取当前用户ID
        Long currentUserId = 1L;
        log.debug("退出团队请求: 团队ID={}, 用户ID={}", teamId, currentUserId);
        
        Team team = teamService.leaveTeam(teamId, currentUserId);
        
        User leader = userService.getUserById(team.getLeaderId());
        List<Long> memberIds = teamService.getTeamMemberIds(teamId);
        int memberCount = memberIds.size();
        int pendingCount = applicationService.getApplicationsByTeamAndStatus(teamId, 
            com.outdoor.model.enums.ApplicationStatus.PENDING).size();
            
        TeamResponse response = TeamResponse.fromEntityWithDetails(
            team, leader, memberCount, pendingCount);
            
        return ApiResponse.success("成功退出团队", response);
    }
}